package xyz.tommy0607.codepedia_helper.action;

import com.intellij.credentialStore.CredentialAttributes;
import com.intellij.credentialStore.CredentialAttributesKt;
import com.intellij.credentialStore.Credentials;
import com.intellij.ide.passwordSafe.PasswordSafe;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.Messages;
import javafx.application.Platform;
import javafx.embed.swing.JFXPanel;
import javafx.scene.Scene;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import org.jdom.JDOMException;
import org.jetbrains.annotations.NotNull;
import xyz.tommy0607.codepedia_helper.Main;

import javax.swing.*;
import java.awt.*;
import java.io.IOException;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.HttpCookie;

public class LogInAction extends AnAction {
    @Override
    public void actionPerformed(@NotNull AnActionEvent e) {
        Messages.showInfoMessage("请选择educoder选项，然后输入Educoder的手机号和密码，接着点击登陆即可", "提示");
        LoginDialog dialog = new LoginDialog(e.getProject());
        dialog.show();
    }

    @Override
    public void update(@NotNull AnActionEvent e) {
        Project project = e.getProject();
        e.getPresentation().setEnabledAndVisible(project != null && Main.getInstance(project) != null);
    }

    private static class LoginDialog extends DialogWrapper {
        private Project project;

        private LoginDialog(Project project) {
            super(true);
            this.project = project;
            init();
            setTitle("Log In for CodePedia");
        }

        @Override
        protected JComponent createCenterPanel() {
            JFXPanel panel = new JFXPanel();
            panel.setPreferredSize(new Dimension(1000, 600));
            Platform.setImplicitExit(false);
            Platform.runLater(() -> {
                CookieManager cookieManager = new CookieManager();
                CookieHandler.setDefault(cookieManager);
                WebView webView = new WebView();
                WebEngine webEngine = webView.getEngine();
                webEngine.load("http://codepedia.trustie.net/users/login/");
                webEngine.locationProperty().addListener((observable, oldValue, newValue) -> {
                    if (newValue.endsWith("trustie.net/") || newValue.endsWith("trustie.net"))
                        for (HttpCookie cookie : cookieManager.getCookieStore().getCookies()) {
                            String name = cookie.getName();
                            String value = cookie.getValue();
                            if (name.equals("sessionid")) {
                                Main.getInstance(project).sessionID = value;
                                CredentialAttributes credentialAttributes = new CredentialAttributes(CredentialAttributesKt.generateServiceName("CodePediaHelper", "codepedia_helper"));
                                Credentials credentials = new Credentials("sessionid", value);
                                PasswordSafe.getInstance().set(credentialAttributes, credentials);
                                Main.getInstance(project).hasLogin = true;

                                ApplicationManager.getApplication().invokeLater(() -> {
                                    this.close(OK_EXIT_CODE);
                                    this.dispose();
                                    Messages.showInfoMessage("Log In Successfully!", "Info");
                                    Main.getInstance(project).reload();
                                }, ModalityState.any());
                                break;
                            }
                        }
                });
                panel.setScene(new Scene(webView));
            });
            return panel;
        }

        @NotNull
        @Override
        protected Action[] createActions() {
            return new Action[]{};
        }
    }


}
